<?php

if(isset($_POST['username']) && isset($_POST['password'])){
	$host="localhost"; // Host name 
	$username="root"; // Mysql username 
	$password=""; // Mysql password 
	$db_name="nlp"; // Database name 
	$tbl_name="login"; // Table name

	// Connect to server and select databse.
	mysql_connect("$host", "$username", "$password") or die("cannot connect"); 
	mysql_select_db("$db_name") or die("cannot select DB");

	// username and password sent from form 
	$myusername=$_POST['username']; 
	$mypassword=$_POST['password'];

	// To protect MySQL injection (more detail about MySQL injection)
	$myusername = stripslashes($myusername);
	$mypassword = stripslashes($mypassword);
	$myusername = mysql_real_escape_string($myusername);
	$mypassword = mysql_real_escape_string($mypassword);

	$encrypted_password = md5($mypassword);

	$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$encrypted_password'";
	$result=mysql_query($sql);

	// Mysql_num_row is counting table row
	$count=mysql_num_rows($result);
	// If result matched $myusername and $mypassword, table row must be 1 row

	if($count==1){
	// Register $myusername, $mypassword and redirect to file "login_success.php"
		session_start();
		$_SESSION['username'] = $myusername;
		$_SESSION['password'] = $mypassword; 
		$_SESSION['authorized'] = true;
		
		if(isset($_GET['url'])){
			header("location: {$_GET['url']}");
		}
		else{
			header("location:index.php");
		}
	} else {
		echo "<font color=\"red\">Wrong Username or Password!</font>";
	}
}
?>

<html>
	<head>
		<title>Login</title>
	</head>

	<body>
		<form action=<?php echo "\"{$_SERVER['PHP_SELF']}\""; ?> method="post">
			<h1>Login</h1>
			<table>
				<tr>
					<td>Username:</td>
					<td><input type="text" name="username" value=<?php if(isset($_POST['username'])) print "\"{$_POST['username']}\""; ?>></td>
				</tr>
				<tr>
					<td>Password:</td>	
					<td><input type="password" name="password"></td>
				</tr>
			</table>
			<input type="submit" text="Login" />
		</form>
		
		<form action="signup.php" method="post">
			<h1>Signup</h1>
			<table>
				<tr>
					<td>Username:</td>
					<td><input type="text" name="username"></td>
				</tr>
				<tr>
					<td>Password:</td>	
					<td><input type="password" name="password"></td>
				</tr>
			</table>
			<input type="submit" text="Sign Up" />
		</form>
	</body>
</html>